package org.dut.community.controller;

import org.dut.community.entity.DiscussPost;
import org.dut.community.entity.Page;
import org.dut.community.service.DiscussPostService;
import org.dut.community.service.ElasticsearchService;
import org.dut.community.service.LikeService;
import org.dut.community.service.UserService;
import org.dut.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.dut.community.util.CommunityConstant.ENTITY_TYPE_POST;

@Controller
public class SearchController {
    @Autowired
    private ElasticsearchService elasticsearchService;
    // 查询帖子点赞数和作者
    @Autowired
    private LikeService likeService;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private DiscussPostService discussPostService;

    @RequestMapping(path="/search",method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model){
        // 搜索结果
        org.springframework.data.domain.Page<DiscussPost> searchResult =
                elasticsearchService.searchByTemplate(keyword, page.getCurrent()-1, page.getLimit());

        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if(searchResult != null){
            for(DiscussPost post : searchResult.getContent()){
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);
                map.put("user",userService.findUserById(post.getUserId()));
                map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST,post.getId()));
                map.put("postReadCount",discussPostService.getPostReadCount(post.getId()));
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("keyword",keyword);

        page.setPath("/search?keyword="+keyword);
        page.setRows(searchResult==null?0:searchResult.getTotalPages());
        return "/site/search";
    }

}
